package com.imdroid.carac.activities;

import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.process.ProcessFactory;
import com.imdroid.carac.process.UserProcess;

/**
 * The screen of the match
 */
public class OptionsMatchPreference extends DialogPreference {
	/**
	 * The tag of the options match preference
	 */
	private String TAG = "OptionsMatchPreference";
	/**
	 * The context of the view
	 */
	private Context context;
	/**
	 * The location
	 */
	private BDLocation currentLocation = null;
	/**
	 * The match code
	 */
	private String matchcode = null;

	/**
	 * The constructor
	 * 
	 * @param context
	 *            the context
	 * @param attrs
	 *            the attributor
	 */
	public OptionsMatchPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		this.setPositiveButtonText("");
	}


	

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.preference.DialogPreference#onPrepareDialogBuilder(android.app
	 * .AlertDialog.Builder)
	 */
	@SuppressWarnings("deprecation")
	protected void onPrepareDialogBuilder(Builder builder) {
		// 添加布局
		LinearLayout layout = new LinearLayout(context);
		layout.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));

		// 生成验证码
		matchcode = getRandomCode();

		// 设置界面
		TextView tv = new TextView(context);
		String text = context.getString(R.string.match_info);
		text = text.replace("%1%", matchcode);
		tv.setText(text);
		tv.setTextAppearance(context,
				android.R.style.TextAppearance_DeviceDefault_Large);
		layout.addView(tv);

		builder.setView(layout);

		(new GetMatchReadyTask(context, R.string.match_info_wait_title,
				R.string.match_info_wait_text)).execute();
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.preference.DialogPreference#onDialogClosed(boolean)
	 */
	protected void onDialogClosed(boolean positiveResult) {
		super.onDialogClosed(positiveResult);

		// 接触配对状态
		new Thread() {
			public void run() {

				try {
					UserProcess process = (UserProcess) ProcessFactory
							.getProcess(UserProcess.class);
					process.stopMatchStatus();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();

	}
	/**
	 * The progressbar async task
	 * 
	 */
	public class GetMatchReadyTask extends AsyncTask<Void, Integer, Exception> {
		ProgressDialog progressDialog;
		protected Context context;
		protected int titleText, messageText;
		// 定位相关
		private LocationClient mLocClient;

		private MyLocationListener myListener = new MyLocationListener();

		/**
		 * The constructor with the context
		 * 
		 * @param context
		 *            the constructor with the context
		 * @param titleText
		 *            the title text
		 * @param messageText
		 *            the message text
		 */
		public GetMatchReadyTask(Context context, int titleText, int messageText) {
			this.context = context;
			this.titleText = titleText;
			this.messageText = messageText;

			// 开始定位
			mLocClient = new LocationClient(IMDroid.getContext());
			mLocClient.registerLocationListener(myListener);
			LocationClientOption option = new LocationClientOption();
			option.setOpenGps(true);// 打开gps
			option.setCoorType("bd09ll"); // 设置坐标类型
			option.setScanSpan(3000);
			mLocClient.setLocOption(option);
			mLocClient.start();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(context, context
					.getResources().getString(titleText), context
					.getResources().getString(messageText));
			progressDialog.setCancelable(true);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		protected Exception doInBackground(Void... params) {
			// 取得本地位置
			int i=0;
			while (currentLocation == null) {
				try {
					if (i>=20)
						return new Exception(context.getString(R.string.parameter_MATCH_fail_no_gps));
					
					Thread.sleep(1 * 1000);
					++i;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			this.publishProgress(50);

			UserProcess process = (UserProcess) ProcessFactory
					.getProcess(UserProcess.class);
			try {
				process.startMatchStatus(currentLocation, matchcode);
			} catch (Exception e) {
				return e;
			}
			this.publishProgress(100);
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		 */
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			progressDialog.setProgress(values[0]);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Exception result) {
			progressDialog.dismiss();
			mLocClient.stop();
			if (result != null) {
				Toast.makeText(context, result.getMessage(), Toast.LENGTH_SHORT)
						.show();
				if (OptionsMatchPreference.this != null
						&& OptionsMatchPreference.this.getDialog() != null)
					OptionsMatchPreference.this.getDialog().dismiss();
			}
		}
	}

	/**
	 * The location listnner
	 * 
	 */
	private class MyLocationListener implements BDLocationListener {

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.baidu.location.BDLocationListener#onReceiveLocation(com.baidu
		 * .location.BDLocation)
		 */
		public void onReceiveLocation(BDLocation arg0) {
			if (arg0 != null){
				Log.d(TAG,
						"Location change--" + arg0.getLatitude() + " - "
								+ arg0.getLongitude());
				currentLocation = arg0;
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.baidu.location.BDLocationListener#onReceivePoi(com.baidu.location
		 * .BDLocation)
		 */
		public void onReceivePoi(BDLocation arg0) {

		}
	}

	/**
	 * Get the random match code
	 * 
	 * @return the random match code
	 */
	private String getRandomCode() {
		int random = (int) (Math.random() * 10000);
		if (random >= 1000)
			return random + "";
		if (random < 10)
			return "000" + random;
		if (random < 100)
			return "00" + random;
		if (random < 1000)
			return "0" + random;
		else
			return "" + random;

	}
}
